package com.steven.ourcontest.collect.view

import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.steven.ourcontest.R
import com.steven.ourcontest.app.AppRouter
import com.steven.ourcontest.base.BaseFragment
import com.steven.ourcontest.collect.adapter.TeamCollectionListAdapter
import com.steven.ourcontest.collect.viewmodel.TeamCollectionViewModel
import kotlinx.android.synthetic.main.fragment_team_collection.*

class TeamCollectionFragment : BaseFragment() {

    private val viewModel: TeamCollectionViewModel by viewModels()
    private val adapter by lazy {
        context?.let { ctx ->
            TeamCollectionListAdapter(ctx) {
                AppRouter.openTeamDetailActivity(ctx, it)
            }
        }
    }

    override fun getViewId(): Int? {
        return R.layout.fragment_team_collection
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
    }

    private fun initView() {
        //refresh
        smart_refresh?.setEnableAutoLoadMore(false)
        smart_refresh?.setEnableRefresh(true)
        smart_refresh?.setRefreshFooter(ClassicsFooter(context))
        smart_refresh?.setRefreshHeader(ClassicsHeader(context))
        smart_refresh?.setOnRefreshListener {
            viewModel.refresh({
                smart_refresh?.finishRefresh()
                adapter?.listData?.clear()
            },{
                smart_refresh?.finishRefresh()
            })
        }
        smart_refresh?.setOnLoadMoreListener {
            viewModel.loadMore({
                smart_refresh?.finishLoadMore()
            },{
                smart_refresh?.finishLoadMore()
            })
        }
        //adapter
        rv_team?.adapter = adapter
        viewModel.teamCollectionsRes.observe(viewLifecycleOwner, Observer {
            adapter?.listData?.addAll(it.data)
            adapter?.notifyDataSetChanged()
        })
        //view
        viewModel.loadMore()
    }
}